<?php

/**
 * usuario actions.
 *
 * @package    sispatr
 * @subpackage usuario
 * @author     Foxsis
 * @version    SVN: $Id: actions.class.php 23810 2009-11-12 11:07:44Z Kris.Wallsmith $
 */
class usuarioActions extends sfActionsFoxsis
{
	public function executeIndex(sfWebRequest $request)
	{
		return $this->forward('usuario', 'list');
	}

	public function executeFilter()
	{
		$filter = new Filtro(
		$this->getRequestParameter(sfActionsFoxsis::FILTER_SESSION_USER_ATTRIBUTE)
		);

		$this->getUser()->setAttribute(
		sfActionsFoxsis::FILTER_SESSION_USER_ATTRIBUTE,
		serialize($filter),
		$this->getModuleName()
		);

		return $this->redirect($this->getModuleName().'/list');
	}

	public function executeNew(sfWebRequest $request)
	{
		$this->new 				= new PreUsuarioForm();
		$this->sign_in			= new sfGuardFormSignin();
		
	}

	public function executeSocios(sfWebRequest $request)
	{
	}

	public function executeSaveRelation(sfWebRequest $request)
	{
		$this->forward404Unless($request->isMethod(sfRequest::POST));

		$form = new DadosUsuarioFilhoForm();

		try
		{
			$form->bind($request->getParameter($form->getName()), $request->getFiles($form->getName()));

			if ($form->isValid())
			{
				//$form->getObject()->setIdUsuarioPai($this->getUser()->getGuardUser()->getId());
				$form->getObject()->setIdUsuarioPai($this->getUser()->getIdDadosUsuario());
				//Salvo o usuário e retorno o objeto
				$dados_usuario = $form->save();
				
				//redireciono para a tela do form principal
				$this->getUser()->setFlash('mensagem', 'Cadastro realizado com sucesso.');
				$this->redirect('formulario/socios');
			}
			else
			{
				throw new Exception($form->getErrorSchema());
			}
		}
		catch(Exception $e)
		{
			$this->getUser()->setFlash('erro', $e->getMessage());
		}

		$this->forward('formulario', 'addSocio');
	}

	public function executeSave(sfWebRequest $request)
	{
		$this->forward404Unless($request->isMethod(sfRequest::POST));
		
		$this->form		= new DadosUsuarioForm($this->getUser()->getFormObject());

		$this->processForm($request, $this->form);

		if($this->getRequestParameter("dados_usuario[tp_usuario]") != "")
			$this->forward('formulario', 'addSocio');
		else
			$this->forward('formulario', 'index');//mudar para index após cadastro pelo admin

	}

	public function executeAdd(sfWebRequest $request)
	{
		$this->forward404Unless($request->isMethod(sfRequest::POST));
		
		$usuario	= ($this->hasRequestParameter('id_dados_usuario')) ? Doctrine::getTable('DadosUsuario')->find($this->getRequestParameter('id_dados_usuario')) : new DadosUsuario();
		
		$form		= new AutoUsuarioForm($usuario);

		try
		{
			$form->bind($request->getParameter($form->getName()), $request->getFiles($form->getName()));

			if ($form->isValid())
			{
				$form->getObject()->setTpUsuario(DadosUsuario::CLIENTE);
				
				$dados_usuario = $form->save();
				$this->getUser()->setFlash('mensagem', 'Cadastro realizado com sucesso. Complete agora suas informações.');
				$this->redirect('formulario/add?id_dados_usuario='.$dados_usuario['id_dados_usuario']);
			}
			else
			{
				throw new Exception($form->getErrorSchema());
			}
		}
		catch(Exception $e)
		{
			$this->getUser()->setFlash('erro', $e->getMessage());
		}

		if($this->getRequestParameter("dados_usuario[tp_usuario]") != "")
			$this->forward('formulario', 'addSocio');
		else
			$this->forward('formulario', 'add');

	}

	public function executeSaveLogIn(sfWebRequest $request)
	{
		$this->forward404Unless($request->isMethod(sfRequest::POST));

		$form = new PreUsuarioForm();

		try
		{
			$form->bind($request->getParameter($form->getName()), $request->getFiles($form->getName()));

			if ($form->isValid())
			{
				$form->getObject()->setTpUsuario(DadosUsuario::CLIENTE);
				//Salvo o usuário e retorno o objeto
				$dados_usuario = $form->save();
				//efetuo o login do usuário
				$this->getUser()->signin($dados_usuario['sfGuardUser'], false);

				//redireciono para a tela do form principal
				$this->getUser()->setFlash('mensagem', 'Cadastro realizado com sucesso. Complete agora suas informações.');
				$this->redirect('formulario/index');
			}
			else
			{

				throw new Exception($form->getErrorSchema());
			}
		}
		catch(Exception $e)
		{
			$this->getUser()->setFlash('erro', $e->getMessage());
		}

		$this->forward('usuario', 'new');
	}

	public function executeEdit(sfWebRequest $request)
	{
		$this->forward404Unless($dados_usuario = Doctrine::getTable('DadosUsuario')->find(array($request->getParameter('id_usuario'))), sprintf('Object dados_usuario does not exist (%s).', $request->getParameter('id_usuario')));
		$this->form = new DadosUsuarioForm($dados_usuario);
	}

	public function executeUpdate(sfWebRequest $request)
	{
		$this->forward404Unless($request->isMethod(sfRequest::POST) || $request->isMethod(sfRequest::PUT));
		$this->forward404Unless($dados_usuario = Doctrine::getTable('DadosUsuario')->find(array($request->getParameter('id_usuario'))), sprintf('Object dados_usuario does not exist (%s).', $request->getParameter('id_usuario')));
		$this->form = new DadosUsuarioForm($dados_usuario);

		$this->processForm($request, $this->form);

		$this->setTemplate('edit');
	}

	public function executeDelete(sfWebRequest $request)
	{
		try
		{
			$request->checkCSRFProtection();

			$this->forward404Unless($dados_usuario = Doctrine::getTable('DadosUsuario')->find(array($request->getParameter('id_usuario'))), sprintf('Object dados_usuario does not exist (%s).', $request->getParameter('id_usuario')));
			$dados_usuario->delete();

			$this->redirect('usuario/index');
		}
		catch(Excepiton $e)
		{
			$this->getUser()->setFlash('erro', $e->getMessage());
			$this->redirect('usuario/index');
		}

	}

	protected function processForm(sfWebRequest $request, sfForm $form)
	{
		try
		{

			$form->bind($request->getParameter($form->getName()), $request->getFiles($form->getName()));

			if ($form->isValid())
			{
				$dados_usuario = $form->save();

				if($this->hasRequestParameter('next_step'))
					$this->redirect($this->getRequestParameter('next_step'));

				if($this->getRequestParameter("dados_usuario['tp_usuario'") != "")
					$this->forward('formulario', 'addSocios');
				else
					$this->forward('formulario', 'index');

			}
			else
			{
				throw new Exception($form->getErrorSchema());
			}
		}
		catch(Exception $e)
		{
			$this->getUser()->setFlash('erro', $e->getMessage());
		}
	}

	public function executeSair($request)
    {

        $this->getUser()->signOut();
        $signout_url = sfConfig::get('app_sf_guard_plugin_success_signout_url', $request->getReferer());

        $this->redirect('' != $signout_url ? $signout_url : '@homepage');
    }
}
